package com.espressif.iot.db;

import java.util.List;

import org.apache.log4j.Logger;

import android.text.TextUtils;

import com.espressif.iot.db.greenrobot.daos.DaoSession;
import com.espressif.iot.db.greenrobot.daos.XqzoneDB;
import com.espressif.iot.db.greenrobot.daos.XqzoneDBDao;
import com.espressif.iot.db.greenrobot.daos.XqzoneDBDao.Properties;
import com.espressif.iot.object.IEspSingletonObject;
import com.espressif.iot.object.db.IXqzoneDBManager;

import de.greenrobot.dao.query.Query;

public class IOTXqzoneDBManager implements IXqzoneDBManager, IEspSingletonObject
{
    private final static Logger log = Logger.getLogger(IOTXqzoneDBManager.class);
    
    private XqzoneDBDao xqzoneDao;
    
    // Singleton Pattern
    private static IOTXqzoneDBManager instance = null;
    
    private IOTXqzoneDBManager(DaoSession daoSession)
    {
    	xqzoneDao = daoSession.getXqzoneDBDao();
    }
    
    public static void init(DaoSession daoSession)
    {
        instance = new IOTXqzoneDBManager(daoSession);
    }
    
    public static IOTXqzoneDBManager getInstance()
    {
        return instance;
    }
    
	@Override
	public void insertOrReplace(int iconid, String zonename) {
		// TODO Auto-generated method stub
		insertOrReplace(-1, iconid, zonename);
	}
	@Override
	public void insertOrReplace(long zoneId, int iconid, String zonename) {
		// TODO Auto-generated method stub
		XqzoneDB zoneDB;
		zoneDB = new XqzoneDB(iconid, zonename);
		xqzoneDao.insertOrReplace(zoneDB);
		log.info(Thread.currentThread().toString() + "##insertOrReplace(zonename=[" + zonename );
	}

	@Override
	public void delete(long zoneId) {
		// TODO Auto-generated method stub
      
	}
	
	@Override
	public void delete(String name) {
		// TODO Auto-generated method stub
		List<XqzoneDB> zoneDBList = __getXqzoneDBList(name);
		xqzoneDao.deleteInTx(zoneDBList);
	}

	private List<XqzoneDB> __getXqzoneDBList(String name) {
		// TODO Auto-generated method stub
       Query<XqzoneDB> query = xqzoneDao.queryBuilder().where(Properties.XqzoneName.eq(name)).build();
       return query.list();
	}
    private XqzoneDB __getApDB(String name)
    {
    	 Query<XqzoneDB> query = xqzoneDao.queryBuilder().where(Properties.XqzoneName.eq(name)).build();
         return query.unique();
    }
    

	@Override
	public void renameDevice(long zoneId, String name) {
		// TODO Auto-generated method stub
		XqzoneDB zoneDB =  __getApDB(zoneId);
		zoneDB.setXqzoneName(name);
		xqzoneDao.update(zoneDB);
	}

	private XqzoneDB __getApDB(long zoneId) {
		// TODO Auto-generated method stub
		Query<XqzoneDB> query = xqzoneDao.queryBuilder().where(Properties.Id.eq(zoneId)).build();
        return query.unique();
	}

	@Override
	public List<XqzoneDB> getAllXqzoneDBList() {
		// TODO Auto-generated method stub
		return xqzoneDao.loadAll();
	}

	@Override
	public XqzoneDB getzoneDB(String name) {
		// TODO Auto-generated method stub
		return __getApDB(name);
	}




    
}
